using System;
using System.IO;
using UnityEngine.Recorder.Input;

namespace UnityEngine.Recorder
{
	[Recorder(typeof(ImageRecorderSettings), "Video", "Unity/Image sequence")]
	public class ImageRecorder : GenericRecorder<ImageRecorderSettings>
	{
		public override bool BeginRecording(RecordingSession session)
		{
			if (!base.BeginRecording(session))
			{
				return false;
			}
			m_Settings.m_DestinationPath.CreateDirectory();
			return true;
		}

		public override void RecordFrame(RecordingSession session)
		{
			if (m_Inputs.Count != 1)
			{
				throw new Exception("Unsupported number of sources");
			}
			Texture2D texture2D = null;
			if (m_Inputs[0] is ScreenCaptureInput)
			{
				texture2D = ((ScreenCaptureInput)m_Inputs[0]).image;
				if (m_Settings.m_OutputFormat == PNGRecordeOutputFormat.EXR)
				{
					Texture2D texture2D2 = new Texture2D(texture2D.width, texture2D.height, TextureFormat.RGBAFloat, mipChain: false);
					texture2D2.SetPixels(texture2D.GetPixels());
					texture2D = texture2D2;
				}
				else if (m_Settings.m_OutputFormat == PNGRecordeOutputFormat.PNG)
				{
					Texture2D texture2D3 = new Texture2D(texture2D.width, texture2D.height, TextureFormat.RGB24, mipChain: false);
					texture2D3.SetPixels(texture2D.GetPixels());
					texture2D = texture2D3;
				}
			}
			else
			{
				BaseRenderTextureInput baseRenderTextureInput = (BaseRenderTextureInput)m_Inputs[0];
				int width = baseRenderTextureInput.outputRT.width;
				int height = baseRenderTextureInput.outputRT.height;
				texture2D = new Texture2D(width, height, (m_Settings.m_OutputFormat == PNGRecordeOutputFormat.EXR) ? TextureFormat.RGBAFloat : TextureFormat.RGBA32, mipChain: false);
				RenderTexture active = RenderTexture.active;
				RenderTexture.active = baseRenderTextureInput.outputRT;
				texture2D.ReadPixels(new Rect(0f, 0f, width, height), 0, 0, recalculateMipMaps: false);
				texture2D.Apply();
				RenderTexture.active = active;
			}
			byte[] bytes;
			string ext;
			switch (m_Settings.m_OutputFormat)
			{
			case PNGRecordeOutputFormat.PNG:
				bytes = texture2D.EncodeToPNG();
				ext = "png";
				break;
			case PNGRecordeOutputFormat.JPEG:
				bytes = texture2D.EncodeToJPG();
				ext = "jpg";
				break;
			case PNGRecordeOutputFormat.EXR:
				bytes = texture2D.EncodeToEXR();
				ext = "exr";
				break;
			default:
				throw new ArgumentOutOfRangeException();
			}
			if (m_Inputs[0] is BaseRenderTextureInput || m_Settings.m_OutputFormat != PNGRecordeOutputFormat.JPEG)
			{
				UnityHelpers.Destroy(texture2D);
			}
			string path = m_Settings.m_BaseFileName.BuildFileName(session, base.recordedFramesCount, texture2D.width, texture2D.height, ext);
			string path2 = Path.Combine(m_Settings.m_DestinationPath.GetFullPath(), path);
			File.WriteAllBytes(path2, bytes);
		}
	}
}
